<?php

namespace App\Http\Controllers\V1;

use App\Helpers\ConfigTrait;
use App\Http\Controllers\Controller;
use App\Http\Resources\ProductListResource;
use App\Http\Resources\ProductResource;
use App\Http\Resources\ProductSpecResource;
use App\Http\Resources\SeckillListResource;
use App\Http\Resources\SpikeResource;
use App\Models\Product;
use App\Models\ProductCate;
use App\Models\ProductSeckill;
use App\Service\ConfigService;
use App\Service\ProductSearch;
use App\Service\ProductService;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;

class ProductsController extends Controller
{
    use ConfigTrait;
    /**
     * 商品搜索
     *
     * @param Request $request
     * $search          多关键词（商品标题，长标题，描述，分类名称，规格名称）
     * $page            分页页码
     * $order           排序 desc|asc (价格，销量，评分  如： price_asc | price_desc)
     * $category_id     分类ID
     * @return array
     */
    public function index(Request $request)
    {
        $page    = $request->input('page', 1);
        $perPage = $request->input('pageSize', 10);

        //新建查询构造器对象，设置只搜索上架商品，设置分页
        $builder = (new ProductSearch())->onSale()->onDelete()->paginate($perPage, $page);

        if ($request->input('category_id') && $category = ProductCate::find($request->input('category_id'))) {
            // 调用查询构造器的类目筛选
            $builder->category($category);
        }

        //搜索词
        if ($search = $request->input('search', '')) {
            $keywords = array_filter(explode(' ', $search));
            // 调用查询构造器的关键词筛选
            $builder->keywords($keywords);
        }

        //排序
        if ($order = $request->input('order', '')) {
            if (preg_match('/^(.+)_(asc|desc)$/', $order, $m)) {
                if (in_array($m[1], ['price', 'sold_count', 'rating', 'sort'])) {
                    // 调用查询构造器的排序
                    $builder->orderBy($m[1], $m[2]);
                }
            }
        } else {
            $builder->defaultOrderBy();
        }
        // whereIn查询
        if ($request->input('maxPrice') || $request->input('minPrice')) {
            $builder->whereIn($request->input('minPrice'), $request->input('maxPrice'));
        }
        $results = app('es')->search($builder->getParams());
        // 通过 collect 函数将返回结果转为集合，并通过集合的 pluck 方法取到返回的商品 ID 数组
        $productIds = collect($results['hits']['hits'])->pluck('_id')->all();
        // 通过 whereIn 方法从数据库中读取商品数据
        $products = Product::query()->
            whereIn('id', $productIds)
            ->orderByRaw(sprintf("FIND_IN_SET(id, '%s')", join(',', $productIds)))
            ->get();
        // 返回一个 LengthAwarePaginator 对象
        $pager = new LengthAwarePaginator($products, $results['hits']['total']['value'], $perPage, $page);
        return $this->success([
            'list' => ProductListResource::collection($pager),
            'count' => $pager->total(),
            'current' => $pager->currentPage(),
        ]);
    }

    /**
     * 获取商品详情
     * @param $id
     * @param ProductService $service
     * @return mixed
     */
    public function show($id, ProductService $service, ConfigService $configService)
    {
        $user = auth('api')->user();
        // 获取 最近下单地址
        if ($user) {
            // 获取 最近下单地址
            $address = $user->orders()->orderBy('created_at','desc')->value('address');
        } else {
            $address = '';
        }
        // 获取产品信息
        $product = $service->getProduct($id, ['images','coupons', 'freight']);

        // 获取产品规格
        $specs = ProductSpecResource::collection($service->getProductSpec($product));

        // 获取产品SKU
        $skus = $service->getProductSkus($product);

        // 秒杀
        $seckill = $product->seckill()->begin()->first();

        // 获取购物车数量
        if ($user = auth('api')->user()) {
            $cartCount = $user->cart()->sum('amount');
        } else {
            $cartCount = 0;
        }
        $freightPrice = $configService->getFreightPrice();
        return $this->success([
            'cart_count' => intval($cartCount),
            'freight_price' => $freightPrice,
            'product' => new ProductResource($product),
            'specs' => $specs,
            'address' => $address,
            'skus' => $skus,
            'seckill' => is_null($seckill) ? '' : new SpikeResource($seckill)
        ]);
    }

    // 获取秒杀产品
    public function getSeckillProducts()
    {

        $secklills = ProductSeckill::with('product')->begin()->first();

//        $tomorrowSeckills = ProductSeckill::with('product')
//            ->where('start_at','>', Carbon::parse($secklills->end_at)->toDateString())->first();
        $tomorrowSeckills = '';
        return $this->success([
            'todaysSecklills' => is_null($secklills) ? '' : new SeckillListResource($secklills),
            'tomorrowSeckills' => $tomorrowSeckills,
        ]);
    }
}
